package com.enlorenz.core.engine.manager;

import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.enlorenz.common.util.TimeUtils;
import com.enlorenz.core.engine.IEngine;
import com.enlorenz.core.engine.exception.EngineControlException;
import com.enlorenz.core.engine.imp.thread.quick.AbstractQuickSleepFirstThread;

/**
 * 检查线程是否存活并且重启
 * @author lcb
 */
public class EngineCheckThread extends AbstractQuickSleepFirstThread{
	protected Logger logger=LoggerFactory.getLogger(this.getClass());
	private List<IEngine> engines;
	private boolean checkLog=true;
	
	public void setCheckLog(boolean checkLog) {
		this.checkLog = checkLog;
	}
	public void setEngines(List<IEngine> engines) {
		this.engines = engines;
	}
	
	@Override
	protected void handle() {
		for(IEngine engine:engines){
			if(checkLog){
				logger.info("线程[{}],状态[{}]",
						engine.getName(),String.valueOf(engine.isAlive()));
			}
			
			if(!engine.isAlive()){
				restartObject(engine);
			}
		}
	}
	/**
	 * 重启线程
	 * @param engine
	 */
	protected void restartObject(IEngine engine){
		doWhenRestartObject(engine);
		try {
			engine.forceRestart();
		} catch (EngineControlException e) {
			e.printStackTrace();
			logger.error("线程[{}]重启失败",engine.getName());
		}
	}
	
	
	protected void doWhenRestartObject(IEngine engine){
		logger.error("线程[{}]在[{}]时间重启",engine.getName(),TimeUtils.format2EnViewDate(new Date()));
	}
}
